<template>
  <el-container class="testAddForm-box">
    <el-header style="height: 25px;">
      <el-row :gutter="10">
        <el-col :span="6">
          <span @click="() => {this.$router.go(-1)}" class="font-blue my-btn">返回上级</span>
        </el-col>
        <el-col :push="3" :span="10"><span>{{this.$route.name}}</span></el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-form
        ref="addform"
        :model="formData"
        label-width="100px"
        size="mini"
        >

        <el-form-item label="试卷名称：" prop="name">
          <el-input v-model="formData.name" placeholder="请输入内容"></el-input>
        </el-form-item>

        <el-form-item label="试卷分类：" prop="class">
          <el-select v-model="formData.class" placeholder="请选择分类">
            <el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="生成类型：" prop="gentype">
          <el-radio-group v-model="formData.gentype">
            <el-radio label="custom">自由选择</el-radio>
            <el-radio label="random">随机生成</el-radio>
          </el-radio-group>
        </el-form-item>


        <!-- 生成类型区分开始 -->
        <!-- 自由选择开始 -->
        <template v-if="testType == 1">
          <el-form-item label="试卷选项：">
            <el-tabs v-model="currTab" @tab-click="(tab) => {this.currTab=tab.name}" tab-position="top" type="border-card">
              <el-tab-pane label="单选" name="single">
                <el-row>
                  <el-col :span="2"><el-button type="primary" @click="openDialog('single')">新增单选</el-button></el-col>
                  <el-col v-if="formQuestions.single && formQuestions.single.length > 0" :span="5">每题分值:<el-input class="myscore-input" v-model="everyScore.single" placeholder="请输入每题分值"></el-input></el-col>
                </el-row>
                <Table
                  border
                  maxHeight="300"
                  :tableData="formQuestions.single"
                  :inits="regTableinits"
                  :operation="regOperationinits">
                  <template slot-scope="rowScope">
                    <el-button @click="remove(rowScope, 'single')" type="text" size="small">移除</el-button>
                  </template>
                </Table>
              </el-tab-pane>
              <el-tab-pane label="多选" name="multiple">
                <el-row>
                  <el-col :span="2"><el-button type="primary" @click="openDialog('multiple')">新增多选</el-button></el-col>
                  <el-col v-if="formQuestions.multiple && formQuestions.multiple.length > 0" :span="5">每题分值:<el-input class="myscore-input" v-model="everyScore.multiple" placeholder="请输入每题分值"></el-input></el-col>
                </el-row>
                <Table
                  maxHeight="300"
                  :tableData="formQuestions.multiple"
                  :inits="regTableinits"
                  :operation="regOperationinits">
                  <template slot-scope="rowScope">
                    <el-button @click="remove(rowScope, 'multiple')" type="text" size="small">移除</el-button>
                  </template>
                </Table>
              </el-tab-pane>
              <el-tab-pane label="判断" name="judge">
                <el-row>
                  <el-col :span="2"><el-button type="primary" @click="openDialog('judge')">新增判断</el-button></el-col>
                  <el-col v-if="formQuestions.judge && formQuestions.judge.length > 0" :span="5">每题分值:<el-input class="myscore-input" v-model="everyScore.judge" placeholder="请输入每题分值"></el-input></el-col>
                </el-row>
                <Table
                  maxHeight="300"
                  :tableData="formQuestions.judge"
                  :inits="regTableinits"
                  :operation="regOperationinits">
                  <template slot-scope="rowScope">
                    <el-button @click="remove(rowScope, 'judge')" type="text" size="small">移除</el-button>
                  </template>
                </Table>
              </el-tab-pane>
              <el-tab-pane label="填空" name="text">
                <el-row>
                  <el-col :span="2"><el-button type="primary" @click="openDialog('text')">新增填空</el-button></el-col>
                  <el-col v-if="formQuestions.text && formQuestions.text.length > 0" :span="5">每题分值:<el-input class="myscore-input" v-model="everyScore.text" placeholder="请输入每题分值"></el-input></el-col>
                </el-row>
                <Table
                  maxHeight="300"
                  :tableData="formQuestions.text"
                  :inits="regTableinits"
                  :operation="regOperationinits">
                  <template slot-scope="rowScope">
                    <el-button @click="remove(rowScope, 'text')" type="text" size="small">移除</el-button>
                  </template>
                </Table>
              </el-tab-pane>
              <el-tab-pane label="问答" name="composite">
                <el-row>
                  <el-col :span="2"><el-button type="primary" @click="openDialog('composite')">新增问答</el-button></el-col>
                  <el-col v-if="formQuestions.composite && formQuestions.composite.length > 0" :span="5">每题分值:<el-input class="myscore-input" v-model="everyScore.composite" placeholder="请输入每题分值"></el-input></el-col>
                </el-row>
                <Table
                  maxHeight="300"
                  :tableData="formQuestions.composite"
                  :inits="regTableinits"
                  :operation="regOperationinits">
                  <template slot-scope="rowScope">
                    <el-button @click="remove(rowScope, 'composite')" type="text" size="small">移除</el-button>
                  </template>
                </Table>
              </el-tab-pane>
            </el-tabs>

          </el-form-item>
        </template>
        <!-- 自由选择结束 -->
        <!-- 随机生成开始 -->
        <template v-if="testType == 2">
          <el-form-item label="生成规则：" prop="genRule">
            <el-select v-model="formData.genRule" placeholder="请选择生成规则">
              <el-option v-for="item in genRuleOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="试卷选项：" prop="testOptions">
            <el-row v-for="(item, index) in formData.testOptions" :key="index" :gutter="5">
              <el-col :span="4">
                <el-select v-model="formData.testOptions[index].class" placeholder="试题分类">
                  <el-option v-for="item in test_classOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-col>
               <el-col :span="4">
                <el-select v-model="formData.testOptions[index].tag" placeholder="标签">
                  <el-option v-for="item in test_flagOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-col>
              <el-col :span="2">
                <el-select v-model="formData.testOptions[index].type" placeholder="题型">
                  <el-option v-for="item in test_typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-col>
              <el-col :span="2">
                <el-select v-model="formData.testOptions[index].degree" placeholder="难度">
                  <el-option v-for="item in test_degreeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <span>每题分值：</span>
                <el-input class="score-input" v-model="formData.testOptions[index].score" placeholder="分数"></el-input>
              </el-col>
              <el-col :span="5">
                <span>数量：</span>
                <el-input-number class="total-input" v-model="formData.testOptions[index].total" placeholder="数量"></el-input-number>
              </el-col>
              <el-col :span="2" style="padding-left: 10px">
                <span class="my-btn font-red" @click="test_deloptions(index)">-删除</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="3">
                <el-button type="primary" @click="test_addoptions">+ 分类</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </template>
        <!-- 随机生成结束 -->
        <!-- 生成类型区分结束 -->

        <el-form-item>
          <el-button v-if="formData.gentype == 'random'" type="primary" @click="save2temp">保存为模板</el-button>
          <el-button type="primary" @click="publish">发布</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </el-form-item>

      </el-form>
    </el-main>

    <!-- 题目选择对话框 S -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="dialogCloseHandle"
      @open="dialogOpenHandle">
      <!-- 筛选部分 S -->
      <el-row :gutter="5">
        <el-col :offset="17" :span="5"><el-input v-model="keyword_input" placeholder="请输入关键词"></el-input></el-col>
        <el-col :span="2"><el-button  @click="keywordSearch" plain>搜索</el-button></el-col>
      </el-row>
      <!-- 筛选部分 E -->
      <Table
        size="small"
        ref="selectTable"
        maxHeight="300"
        :tableData="tableData"
        :inits="tableinits"
        @select="select_table"
        canSelect>
      </Table>
      <!-- 分页器 S -->
      <el-row>
        <el-col>
          <el-pagination
            layout="prev, pager, next"
            :page-size="15"
            :current-page="pageNo"
            :total="total"
            @current-change="pageNoChange">
          </el-pagination>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogOKHandle">确 定</el-button>
      </span>
      </el-dialog>
    <!-- 题目选择对话框 E -->
  </el-container>
</template>

<script>
import Table from '@/components/Table'
import { quest_fmt_getQuestions } from '@/util/dataFMT'

export default {
  name: 'TestAddForm',
  components: {
    Table
  },
  mounted () {
    this._testid = this.$route.params.id
    if (!this._initSelectedId) this._initSelectedId = [] // 初始化对应数组
    if (this._testid || this._testid == 0) { // 编辑表单
      this._pageType = 'edit'
      // 获取此表单数据并初始化
      this.$API.getTest(this._testid)
      .then(data => {
        this._initForm(data)
      })
    } else { // 新增表单
      this._pageType = 'add'
    }


    this.$API.getAllQuestClass()
    .then(data => {
    	console.log(data)
      this.test_classOptions = data.map(item => {
        return {label: item.name, value: item.id}
      })
    })
    this.$API.getAllLabellist()
    .then(data => {
      this.test_flagOptions = data.map(item => {
        return {label: item.name, value: item.id}
      })
    })
    this.$API.getAllTestClass()
    .then(data => {
      this.classOptions = data.map(item => {
        return {label: item.name, value: item.id}
      })
    })
  },
  data () {
    return {
      keyword_input: '',
      _testid: '',
      _pageType: '',
      currTab: 'single',
      everyScore: { // 每题分值
        single: '',
        multiple: '',
        judge: '',
        text: '',
        composite: ''
      },
      mutiSelected: [],
      regTableinits: [
        { label: '编号', width: '140', prop: 'id' },
        { label: '题干', prop: 'name' },
        { label: '分值', width: '140', prop: 'score' }
      ],
      regOperationinits: { width: '140', label: '操作' },
      tableData: [],
      tableSelected: [],
      tableinits: [
        { label: '编号', width: '80', prop: 'id' },
        { label: '题目', prop: 'name', notooltip: true},
        // { label: '题型', width: '50', prop: 'type' },
        { label: '难易', width: '50', prop: 'degree' },
        { label: '分类', width: '50', prop: 'class' },
        { label: '参考文献', width: '100', notooltip: true, prop: 'literature' },
//      { label: '适用人群', width: '120', prop: 'intend' },
        { label: '标签', width: '50', prop: 'tag' },
        { label: '更新时间', width: '120', prop: 'updateTime' },
        { label: '创建时间', width: '120', prop: 'createTime' }
      ],
      pageNo: 1,
      total: 0,
      dialogVisible: false,
      formData: {
        name: '',
        class: '',
        gentype: '',
        genRule: '',
        testOptions: [{
          tag: '',
          class: '',
          degree: '',
          total: '',
          score: '',
          type: ''
        }]
      },
      classOptions: [],
      genRuleOptions: [{
        label: '每位考生试卷相同',
        value: 'unique'
      }, {
        label: '每位考生试卷随机',
        value: 'random'
      }],
      test_classOptions: [],
      test_flagOptions:[],
      test_degreeOptions: [{
        label: '全部',
        value: ''
      }, {
        label: '简单',
        value: 'easy'
      }, {
        label: '中等',
        value: 'medium'
      }, {
        label: '困难',
        value: 'hard'
      }],
      test_typeOptions: [{
        label: '单选',
        value: 'single'
      }, {
        label: '多选',
        value: 'multiple'
      }, {
        label: '判断',
        value: 'judge'
      }, {
        label: '填空',
        value: 'text'
      }, {
        label: '问答',
        value: 'composite'
      }],
      formQuestions: {
        single: [],
        multiple: [],
        judge: [],
        text: [],
        composite: []
      },
      history: {}
		}
  },
  computed: {
    testType () {
      switch (this.formData.gentype) {
        case 'custom':
          return 1;
        case 'random':
          return 2;
        default: 0;
      }
    }
  },
  watch: {
    tableData (curr, old) {
      this.count_selected()
      let init_arr = []
      curr.forEach(item => {
        this._tempTotalSelected.forEach(iitem => {
          if (iitem.id == item.id) {
            init_arr.push(item)
            this.$nextTick(() => {
              this.$refs.selectTable.toggleRowSelection(item, true)
            })
          }
        })
      })
      // 初始化history
      this.select_table(init_arr)
      // 保存上一页的选中状态
      this.count_selected()
    },
    everyScore: {
      handler: function (nval) {
        this.formQuestions[this.currTab].forEach(item => {
          item.score = nval[this.currTab]
        })
        this.formQuestions[this.currTab] = [].concat(this.formQuestions[this.currTab])
      },
      deep: true
    }
  },
  methods: {
    select_table(row) {
			this.history['index'+this.pageNo] = JSON.parse(JSON.stringify(row));
		},
    count_selected() {
      let arr = []
      for(const prop in this.history) {
        arr = arr.concat(this.history[prop])
      }
      this._tempTotalSelected = this._tempTotalSelected.concat(arr)
      let result = []
      this._tempTotalSelected.forEach(function(item) {
           if(result.findIndex((ele) => {return ele.id == item.id}) < 0) {
               result.push(item)
           }
      });
      this._tempTotalSelected = result
    },

    keywordSearch () { // 搜索关键字
      this.count_selected()
      this.pageNo = 1
      this.history = {}
      this.$API.getQuestions({page: this.pageNo, type: this.openQuestType, keyword: this.keyword_input})
      .then(data => {
        this.total = data.total
        this.tableData = quest_fmt_getQuestions(data.data)
      })
    },
    remove ({rowScope}, questType) { // 删除已选的题目
      this.formQuestions[questType].forEach((item, index) => {
        if (item.id == rowScope.row.id) {
          this.formQuestions[questType].splice(index, 1)
        }
      })
    },
    openDialog(questType) {
      this.openQuestType = questType
      this.dialogVisible = true
    },
    dialogOpenHandle () { // 打开选择题目表单要作的事
      this.keyword_input = ''
      this.pageNo = 1
      this.history = {}
      this._tempTotalSelected = this.formQuestions[this.openQuestType]

      // 初始化列表
      this.$API.getQuestions({page: this.pageNo, type: this.openQuestType})
      .then(data => {
        this.total = data.total
        this.tableData = quest_fmt_getQuestions(data.data)
      })
    },
    dialogCloseHandle (done) { // 关闭选择题目表单要作的事

      // 清空
      this.tableSelected = []
      this.openQuestType = ''
      this.tableData = []

      done()
    },
    dialogOKHandle () { // 对话框确定事件
      this.count_selected()
      this.formQuestions[this.openQuestType] = this._tempTotalSelected
      this.everyScore[this.openQuestType] = this.formQuestions[this.openQuestType][0] && this.formQuestions[this.openQuestType][0].score // 给每空多少分填入初始化分值

      this.dialogVisible = false // 关闭对话框
    },
    pageNoChange (pageNo) {
      this.pageNo = pageNo
      this.$API.getQuestions({page: this.pageNo, type: this.openQuestType, keyword: this.keyword_input})
      .then(data => {
        this.tableData = quest_fmt_getQuestions(data.data)
      })
    },
    getIndex (typeName) {
      switch (typeName) {
        case '单选':
          return 'single';
        case '多选':
          return 'multi';
        case '判断':
          return 'judge';
        case '填空':
          return 'text';
        case '问答':
          return 'composite';
        default: ;
      }
    },
    getCName (type) {
      switch (type) {
        case 'single':
          return '单选';
        case 'multiple':
          return '多选';
        case 'judge':
          return '判断';
        case 'text':
          return '填空';
        case 'composite':
          return '问答';
        default: ;
      }
    },
    save () {
      let params = this._genPostParams(this.formData);
      if (!params) return ;
      if (this._pageType == 'edit') {
        this.$API.updateTest(this._testid, Object.assign(params, {action: 'save'}))
        .then(data => {
          this.$router.replace('/home/testList')
        })
      } else {
        this.$API.addTest(Object.assign(params, {action: 'save'}))
        .then(data => {
          this.$router.replace('/home/testList')
        })
      }
    },
    save2temp () {
      let params = this._genPostParams(this.formData);
      if (!params) return ;
      if (this._pageType == 'edit') {
        this.$API.updateTest(this._testid, Object.assign(params, {action: 'template'}))
        .then(data => {
          this.$router.replace('/home/testList')
        })
      } else {
        this.$API.addTest(Object.assign(params, {action: 'template'}))
        .then(data => {
          this.$router.replace('/home/testList')
        })
      }
    },
    publish () {
      let params = this._genPostParams(this.formData);
      if (!params) return ;
      if (this._pageType == 'edit') {
        this.$API.updateTest(this._testid, Object.assign(params, {action: 'publish'}))
        .then(data => {
          this.$router.replace('/home/testList')
        })
      } else {
        this.$API.addTest(Object.assign(params, {action: 'publish'}))
        .then(data => {
          this.$router.replace('/home/testList')
        })
      }
    },
    test_addoptions () {
      this.formData.testOptions.push({ class: '', degree: '', total: '', score: '', type: '' })
    },
    test_deloptions (index) {
      this.formData.testOptions.splice(index, 1)
    },
    _genPostParams(formData) {
      let output = {}
      output.name = formData.name
      output.exam_category_id = formData.class
      output.type = formData.gentype
      if (formData.gentype == 'custom') { // 自由选择
        let arr = []; // 已选择的问题
        for (let prop in this.formQuestions) {
          this.formQuestions[prop].forEach(item => {
            item.type = prop
          })
          arr = arr.concat(this.formQuestions[prop])
        }
        try {
          output.question = JSON.stringify(arr.map(item => { // 转化为请求所需的数据格式
            if (!item.score) {
              throw Error(`${this.getCName(item.type)}题的分值不能为空`)
            }
            return {id: item.id, score: item.score, type: item.type, name: item.name}
          }))
        } catch (err) {
          this.$message.error(err.message)
          return false
        }
      } else { // 随机生成
        output.gtype = formData.genRule
        output.question = JSON.stringify(formData.testOptions.map(item => {
          return {id: item.class, difficulty: item.degree, quantity: item.total, score: item.score, type: item.type}
        }))
      }
      return output
    },
    _initForm(data) {
      let { exam_category_id, gtype, name, question, type } = data

      let fd = { // 表单初始值
        name,
        class: exam_category_id,
        gentype: type
      }

      if (type == 'custom') { // 自由选择
        let questions = JSON.parse(question)
        let formQuestions = {}
        questions.forEach(item => {
          if (!formQuestions[item.type]) formQuestions[item.type] = [] // 初始化对应数组
          formQuestions[item.type].push(item)
          this._initSelectedId.push(item.id)
        })
        this.formQuestions = Object.assign(this.formQuestions, formQuestions)
        for (let prop in this.formQuestions) {
          if (this.formQuestions[prop].length > 0) {
            this.everyScore[prop] = this.formQuestions[prop][0].score // 给每空多少分填入初始化分值
          } else {
            this.everyScore[prop] = ''
          }
        }
        console.log(this._initSelectedId)
      } else { // 随机选择
        fd.genRule = gtype
        fd.testOptions = JSON.parse(question).map(item => {
          return {class: item.id, degree: item.difficulty, total: item.quantity, score: item.score, type: item.type}
        })
      }

      this.formData = Object.assign({}, this.formData, fd)

    }
  }
}
</script>

<style>
  .testAddForm-box {
    text-align: left;
  }
  .testAddForm-box .my-label {
    margin-right: 10px;
  }
  .testAddForm-box .score-input {
    width: 40%;
    min-width: 60px;
  }
  .testAddForm-box .total-input {
    width: 60%;
    min-width: 120px;
  }
  .testAddForm-box .myscore-input {
    width: 50%;
    min-width: 130px;
    margin-left: 5px;
  }
  .testAddForm-box .font-blue {
    color: #0366bb;
  }
  .testAddForm-box .font-red {
    color: #F56C6C;
  }
  .my-btn {
    cursor: pointer;
  }
</style>
